import { unescape } from 'querystring';

export class Utils {
    static clone(origin) {
        return Object.assign({}, origin);
    }

    static deepClone(origin) {
        const originProto = Object.getPrototypeOf(origin);
        return Object.assign(Object.create(originProto), origin);
    }

    static mergeTo(target, ...sources) {
        return Object.assign(target, ...sources);
    }

    static merge(...sources) {
        return Object.assign({}, ...sources);
    }

    static guidGenerator() {
        function s4() {
            return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
        }
        return `${s4()}${s4()}-${s4()}-${s4()}-${s4()}-${s4()}${s4()}${s4()}`;
    }

    static getQueryString(url, name) {
        let paras = url.split('?');
        if (paras.length === 2) {
            paras = paras[1];
            const reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)', 'i');
            const r = paras.match(reg);
            if (r !== null) {
                return unescape(r[2]);
            }
            return null;
        } else {
            return null;
        }
    }

    static replaceEnter(mystr) {
        if (mystr == null || mystr === '') {
            return '';
        } else {
            return mystr.replaceAll('\n', '<br/>');
        }
    }

    /**
     * 去掉所有的html标记
     * @param str html
     */
    static delHtmlTag(str) {
        return str.replace(/<[^>]+>/g, '');
    }

    static getParamsObjFromUrl(url) {
        let obj = {};
        if (Utils.isEmpty(url)) {
            return obj;
        } else {
            const wh = url.lastIndexOf('?');
            if (wh !== -1) {
                const search = url.substr(wh);
                obj = Utils.getUrlRequest(search);
            }

        }
        return obj;
    }

    static getUrlRequest(url) {
        const theRequest = {};
        if (url.indexOf('?') !== -1) {
            const str = url.substr(1);
            if (str.indexOf('&') !== -1) {
                const strs = str.split('&');
                for (let i = 0; i < strs.length; i++) {
                    theRequest[strs[i].split('=')[0]] = decodeURIComponent(strs[i].split('=')[1]);
                }
            } else {
                theRequest[str.split('=')[0]] = decodeURIComponent(str.split('=')[1]);
            }
        }
        return theRequest;
    }

    static getUrlFromParamsObj(url, paramsObj) {
        const wh = url.lastIndexOf('?');
        let u = url;
        if (wh === -1) {
            u = u + '?';
        } else {
            u = url.substring(0, wh + 1);
        }
        for (const key in paramsObj) {
            if (paramsObj.hasOwnProperty(key)) {
                const value = paramsObj[key];
                u = u + key + '=' + value + '&';
            }
        }
        u = u.substr(0, u.length - 1);
        return u;
    }

    static decimal(num, v) {
        const n = parseFloat(num);
        const vv = Math.pow(10, v);
        return Math.round(n * vv) / vv;
    }



    static isEmpty(value) {
        return value == null || (Utils.isString(value) && value.length === 0);
    }

    static isNotEmpty(value) {
        return Utils.isString(value) && value.length > 0;
    }

    static isUndefined(value) {
        return typeof value === 'undefined';
    }

    static isDefined(value) {
        return typeof value !== 'undefined';
    }

    static isObject(value) {
        // http://jsperf.com/isobject4
        return value !== null && typeof value === 'object';
    }

    static isBlankObject(value) {
        return value !== null && typeof value === 'object' && !Object.getPrototypeOf(value);
    }

    static isString(value) {
        return typeof value === 'string';
    }

    static isNumber(value) {
        return typeof value === 'number';
    }

    static isDate(value) {
        return Object.prototype.toString.call(value) === '[object Date]';
    }

    static isArray(value) {
        return Array.isArray;
    }

    static isFunction(value) {
        return typeof value === 'function';
    }

    static format(str, args) {
        let reg;
        let formatStr = str;
        if (Utils.isDefined(args) && Utils.isObject(args)) {
            for (const key in args) {
                if (args.hasOwnProperty(key) && args[key] != null) {
                    reg = new RegExp('({' + key + '})', 'g');
                    formatStr = formatStr.replace(reg, args[key]);
                }
            }
        }
        return formatStr;
    }

    static getDevice() {
        const u = navigator.userAgent;
        let device = 'PC';
        if (u.indexOf('Android') > -1 || u.indexOf('Linux') > -1) {
            device = 'ANDROID';
        }
        if (u.indexOf('iPhone') > -1) {
            device = 'IOS';
        }

        return device;
    }

    static isWeixin() {
        const ua = navigator.userAgent.toLowerCase(); // 获取判断用的对象
        if (ua.match(/MicroMessenger/i) && ua.match(/MicroMessenger/i)[0] === 'micromessenger') {
            return true;
        } else {
            return false;
        }
    }

    static isOnline() {
        return new Promise((resolve, reject) => {
            const img = new Image();
            img.id = 'test_is_online';
            img.onload = function () {
                document.body.removeChild(
                    document.getElementById('test_is_online'));
                resolve(true);
            };
            img.onerror = function () {
                document.body.removeChild(
                    document.getElementById('test_is_online'));
                resolve(false);
            };
            img.src = 'http://test.i-cambio.com/web/dist//img/test.png';
            img.style.display = 'none';
            document.body.appendChild(img);
        });
    }

    static money(m) {
        const numberMoney = Number(m);
        if (isNaN(numberMoney)) {
            return 0
        } else {
            return numberMoney;
        }
    }

    static getQueryBySearch(key, search?) {
        const s = search || window.location.search;
        const reg = new RegExp('(^|&)' + key + '=([^&]*)(&|$)', 'i');
        const r = s.substr(1).match(reg);
        if (r != null) {
            return decodeURIComponent(r[2]);
        }
        return null;
    }

    static reloadIOS() {
        try {
            const u = navigator.userAgent;
            const isiOS = Boolean(u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/)); // ios终端
            if (isiOS) {
                setTimeout(() => window.location.reload(), 500);
            }
        } catch (e) {

        }
    }

    static remove$Prefix(obj: any) {
        if (Utils.isObject(obj)) {
            const keys = Object.keys(obj);
            const o = <any>{};
            keys.forEach((value, index) => {
                if (!value.startsWith('$')) {
                    o[value] = obj[value];
                }
            });
            return o;
        } else {
            return obj;
        }
    }

    static getRandomNum(min, max) {
        const range = max - min;
        const rand = Math.random();
        return (min + Math.round(rand * range));
    }
}
